<template>
  <div id="map" class="map-container" />
</template>

<script>
/* global BMap:readonly */
export default {
  name: 'BaiduMap',
  props: {
    apiKey: {
      type: String,
      required: true
    },
    center: {
      type: Object,
      default: () => ({ lng: 116.404, lat: 39.915 })
    },
    zoom: {
      type: Number,
      default: 11
    },
    markers: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    markers: 'updateMarkers'
  },
  created() {
    this.loadBaiduMapScript()
  },
  methods: {
    loadBaiduMapScript() {
      if (typeof BMap !== 'undefined') {
        this.initializeMap()
        return
      }
      const script = document.createElement('script')
      script.src = `http://api.map.baidu.com/api?v=3.0&ak=${this.apiKey}&callback=initBaiduMap`
      script.onerror = () => {
        console.error('Baidu Map script load failed.')
      }

      document.head.appendChild(script)

      window.initBaiduMap = () => {
        if (typeof BMap !== 'undefined') {
          this.initializeMap()
        } else {
          console.error('BMap is still undefined after callback.')
        }
      }
    },
    initializeMap() {
      this.map = new BMap.Map('map')
      const point = new BMap.Point(this.center.lng, this.center.lat)
      this.map.centerAndZoom(point, this.zoom)
      this.map.enableScrollWheelZoom(true) // 启用滚轮放大缩小
      this.updateMarkers()
    },
    updateMarkers() {
      if (!this.map) return
      this.map.clearOverlays()
      this.markers.forEach(marker => {
        const point = new BMap.Point(marker[0], marker[1])
        const markerInstance = new BMap.Marker(point)
        this.map.addOverlay(markerInstance)
      })
    }
  }
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
}
</style>
